/***************************************************************
*  Copyright (c) 2009 by GroupMe! Team (www.groupme.net)
*  All rights reserved.
*
*  This file is part of the GroupMe! Project. Source code of 
*  this project is closed and redistribution of this code is
*  prohibited. 
*  
*  Contact: http://www.groupme.net
*
*  This copyright notice MUST APPEAR in all copies of the file!
***************************************************************/
package net.groupme.controller.oauth;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.oauth.OAuth;
import net.oauth.OAuthAccessor;
import net.oauth.OAuthMessage;
import net.oauth.server.OAuthServlet;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

/**
 * This class controls the OAuth authorization, which enables other applications to act on behalf
 * of a GroupMe! user, if the GroupMe! user has authorized the application.<br/>
 * In particular, this controller handles the authorization requests.
 * 
 * @author Fabian Abel, <a href="mailto:abel@l3s.de">abel@l3s.de</a>
 * @author last edited by: $Author: fabian $
 * 
 * @version created on Feb 26, 2009
 * @version $Revision: 1.2 $ $Date: 2009-03-12 10:12:16 $
 */
public class OAuthAuthorizeController implements Controller {

	/** Logger for this class and subclasses */
	protected final Log logger = LogFactory.getLog(getClass());
	
	/* (non-Javadoc)
	 * @see org.springframework.web.servlet.mvc.Controller#handleRequest(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		logger.info("OAuth: Authorization Request.");
		try{
            OAuthMessage requestMessage = OAuthServlet.getMessage(request, null);
            requestMessage = OAuthProvider.prepare(requestMessage);
            
            OAuthAccessor accessor = OAuthProvider.getAccessor(requestMessage);
           
            if (Boolean.TRUE.equals(accessor.getProperty("authorized"))) {
                // already authorized send the user back
                returnToConsumer(request, response, accessor);
            } else if(request.getParameter(OAuthProtocol.AUTHORIZATION_GRANTED) != null && Boolean.parseBoolean(request.getParameter(OAuthProtocol.AUTHORIZATION_GRANTED))
            		&& request.getParameter(OAuthProtocol.USER) != null){
            	 // set userId in accessor and mark it as authorized
	            OAuthProvider.markAsAuthorized(accessor, request.getParameter(OAuthProtocol.USER));
	            
            	returnToConsumer(request, response, accessor);
            } else {
                return sendToAuthorizePage(request, response, accessor);
            }
        
        } catch (Exception e){
            OAuthProvider.handleException(e, request, response, true);
        }
		return null;
	}
	
	    
	    private ModelAndView sendToAuthorizePage(HttpServletRequest request, 
	            HttpServletResponse response, OAuthAccessor accessor)
	    throws IOException, ServletException{
	    	ModelAndView mav = new ModelAndView(OAuthProtocol.VIEW_AUTHORIZATION);
	        String callback = request.getParameter("oauth_callback");
	        if(callback == null || callback.length() <=0) {
	            callback = "none";
	        }
	        String consumer_description = (String)accessor.consumer.getProperty("description");
	        request.setAttribute("CONS_DESC", consumer_description);
	        request.setAttribute("CALLBACK", callback);
	        request.setAttribute("TOKEN", accessor.requestToken);
//	        request.getRequestDispatcher //
//	                    ("/authorization.jsp").forward(request,
//	                        response);   
	        return mav;
	    }
	    
	    private void returnToConsumer(HttpServletRequest request, 
	            HttpServletResponse response, OAuthAccessor accessor)
	    throws IOException, ServletException{
	        // send the user back to site's callBackUrl
	        String callback = request.getParameter("oauth_callback");
	        if("none".equals(callback) 
	            && accessor.consumer.callbackURL != null 
	                && accessor.consumer.callbackURL.length() > 0){
	            // first check if we have something in our properties file
	            callback = accessor.consumer.callbackURL;
	        }
	        
	        if( "none".equals(callback) ) {
	            // no call back it must be a client
	            response.setContentType("text/plain");
	            PrintWriter out = response.getWriter();
	            out.println("You have successfully authorized '" 
	                    + accessor.consumer.getProperty("description") 
	                    + "'. Please close this browser window and click continue"
	                    + " in the client.");
	            out.close();
	        } else {
	            // if callback is not passed in, use the callback from config
	            if(callback == null || callback.length() <=0 )
	                callback = accessor.consumer.callbackURL;
	            String token = accessor.requestToken;
	            if (token != null) {
	                callback = OAuth.addParameters(callback, "oauth_token", token);
	            }

	            response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
	            response.setHeader("Location", callback);
	            System.out.println(callback);
	        }
	    }


}

